from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from StudyPlatform.models import Courses, PlayHistory, CourseVideos, UserComment
import datetime


@login_required(login_url='login')
def videoPlayer(request, subject, course_id, course_video_id):
    now = datetime.datetime.now()
    course_id = int(course_id)
    course_video_id = int(course_video_id)
    course = Courses.objects.filter(id=course_id).values("videoname", "videourl", "coursename", "courseurl", "id")[0]
    courseVideos = CourseVideos.objects.filter(courses_id=course_id).all()
    # 讲课程id放在list中,来将切换视频的功能等价于操作list
    courseIdList = list(CourseVideos.objects.filter(courses_id=course_id).values_list("id", flat=True))
    index = courseIdList.index(course_video_id)
    length = len(courseIdList)
    if index + 1 < length:
        current = courseIdList[index + 1]
    else:
        current = 0
    # 设置播放历史
    if PlayHistory.objects.filter(courses_id=course_id):
        PlayHistory.objects.filter(courses_id=course_id).update(play_time=now)
    else:
        PlayHistory.objects.create(user_id=request.user.id, courses_id=course_id, play_time=now)
    # 评论内容
    userComments = UserComment.objects.filter(courses_id=course_id).all()
    context = {
        "course": course,
        "subject": subject,
        "courseVideos": courseVideos,
        "course_video_id": course_video_id,
        "page": index + 1,
        "length": length,
        "current": current,
        "userComments": userComments,
    }
    return render(request, 'video_player.html', context)


# 提交评论内容
@login_required(login_url='login')
def toComment(request):
    if request.method == "POST":
        now = datetime.datetime.now()
        my_comment = request.POST.get("my_comment")
        courses_id = int(request.POST.get("courses_id"))
        UserComment.objects.create(words=my_comment, user_id=request.user.id, courses_id=courses_id, commenttime=now)
        userComments = UserComment.objects.filter(courses_id=courses_id).all()
        context = {
            "userComments": userComments,
        }
        return render(request, 'ajax/ajax_user_comment.html', context)
